package com.excellent.mvvm.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author: lw
 * @date: 2021/9/28 19:57
 * @description：App相关的辅助类
 */
public class AppUtils {

    /**
     * 获取应用程序名称
     */

    public static synchronized String getAppName(Context context) {

        try {

            PackageManager packageManager = context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo(

                    context.getPackageName(), 0);

            int labelRes = packageInfo.applicationInfo.labelRes;

            return context.getResources().getString(labelRes);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    public static String getApplicationId(Context context) {

        return context.getApplicationContext().getPackageName();
    }


    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */

    public static synchronized String getVersionName(Context context) {

        try {

            PackageManager packageManager = context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo(

                    context.getPackageName(), 0);

            return packageInfo.versionName;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */

    public static synchronized int getVersionCode(Context context) {

        try {

            PackageManager packageManager = context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo(

                    context.getPackageName(), 0);

            return packageInfo.versionCode;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return 0;

    }


    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */

    public static synchronized String getPackageName(Context context) {

        try {

            PackageManager packageManager = context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo(

                    context.getPackageName(), 0);

            return packageInfo.packageName;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getAndroidVersion() {
        return Build.VERSION.RELEASE;
    }

    public static int getAndroidSDKVersion() {
        return Build.VERSION.SDK_INT;
    }


    /**
     * 获取图标 bitmap
     *
     * @param context
     */

    public static synchronized Bitmap getBitmap(Context context) {

        PackageManager packageManager = null;

        ApplicationInfo applicationInfo = null;

        try {

            packageManager = context.getApplicationContext()

                    .getPackageManager();

            applicationInfo = packageManager.getApplicationInfo(

                    context.getPackageName(), 0);

        } catch (PackageManager.NameNotFoundException e) {

            applicationInfo = null;

        }

        Drawable d = packageManager.getApplicationIcon(applicationInfo); //xxx根据自己的情况获取drawable

        BitmapDrawable bd = (BitmapDrawable) d;

        Bitmap bm = bd.getBitmap();

        return bm;

    }


    /**
     * 获取application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值 ， 或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context ctx, String key) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo，因为友盟设置的meta-data是在application标签中
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        //key要与manifest中的配置文件标识一致
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return resultData;
    }

    public static String getChannel(Context context) {
        return getAppMetaData(context, "UMENG_CHANNEL");
    }

    public static String getMarketChannel(Context context) {
        return getAppMetaData(context, "MARKET_CHANNEL");
    }


    public static String getAppLinkScheme(Context context) {

        return getApplicationPlaceholders(context, "SCHEME_NAME");
    }

    /**
     * 在Activity获取 manifestPlaceholders 的值
     * <p>
     * 注意:在AndroidManifest.xml 该Activity标签下加上  <meta-data  android:name="label111" android:value="${label}" />
     *
     * @param context
     * @param key
     * @return
     */
    public static String getActivityPlaceholders(Context context, String key) {

        String placeholdersValues = "";
        try {
            ActivityInfo appInfo = context.getPackageManager().getActivityInfo(((Activity) context).getComponentName(), PackageManager.GET_META_DATA);//Activity中
            if (appInfo == null) {
                return "";
            }
            Bundle metaData = appInfo.metaData;
            if (metaData == null) {
                return "";
            }
            placeholdersValues = metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return placeholdersValues;
    }


    /**
     * 在Application获取 manifestPlaceholders 的值
     *
     * @param context
     * @param key
     * @return
     */
    public static String getApplicationPlaceholders(Context context, String key) {

        String placeholdersValues = "";
        try {
            //services receiver只是改个名字类似 ServiceInfo
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);//Application中
            if (appInfo == null) {
                return "";
            }
            Bundle metaData = appInfo.metaData;
            if (metaData == null) {
                return "";
            }
            placeholdersValues = metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return placeholdersValues;
    }


    public static void setAppMetaData(Context ctx, String key, String value) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo，因为友盟设置的meta-data是在application标签中
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        //key要与manifest中的配置文件标识一致
                        applicationInfo.metaData.putString(key, value);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }


    public static Context getAppContext() {
        Application mApplication = null;
        try {
            mApplication = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return mApplication;
    }

    /*
     * 判断服务是否启动,context上下文对象 ，className服务的name
     */
    public static boolean isServiceRunning(Context mContext, String className) {

        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            LogUtils.i("serviceList===" + serviceList.get(i).service.getClassName() + "---className==" + className);
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        LogUtils.i("serviceList===---isRunning==" + isRunning);
        return isRunning;
    }

}
